//
//  MqMainBrandTableViewController.m
//  Meiqi
//
//  Created by lanou on 16/1/12.
//  Copyright © 2016年 KFC. All rights reserved.
//

#import "MqMainBrandTableViewController.h"
#import "PKRequestManager.h"
#import "MqMainbrandModel.h"
#import <UIImageView+WebCache.h>
#import "MqMainBrandHeadTableView.h"
#import "MqDetailBrandViewController.h"

@interface MqMainBrandTableViewController ()

//cell分区数组
@property (nonatomic ,strong)NSMutableArray *listArray;

//cell整个字典
@property (nonatomic ,strong)NSMutableDictionary *listDic;

//表头数组
@property (nonatomic ,strong)NSMutableArray *hotArray;

@property (nonatomic ,strong)MqMainBrandHeadTableView *headView;

@end

@implementation MqMainBrandTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [self setUpData];
    
    //注册
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"brand"];
    
    self.tableView.rowHeight = 50;
    
    //添加表头
    _headView = [[MqMainBrandHeadTableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 100)];
    self.tableView.tableHeaderView = _headView;
    
    
}

//加载数据
- (void)setUpData
{
    [PKRequestManager requestWithUrlString:@"http://p.biketo.com/api/app/BrandList" parDic:nil Method:GET finish:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
       
        _listDic = [NSMutableDictionary dictionary];
        
        NSDictionary *oneDic = dic[@"data"][@"data"];
        NSDictionary  *list = oneDic[@"list"];
        
        NSArray *keys = list.allKeys;
        
        for (NSString *key in keys) {
            
            NSArray *values = list[key];
            
            NSMutableArray *tempArray = [NSMutableArray array];
            
            for (NSDictionary *modelDic in values) {
                
                MqMainbrandModel *model = [[MqMainbrandModel alloc] init];
                [model setValuesForKeysWithDictionary:modelDic];
                
                [tempArray addObject:model];
            }
            //赋值到字典中
            [self.listDic setObject:tempArray forKey:key];
        }
        //排序
        NSArray *array = [keys sortedArrayUsingSelector:@selector(compare:)];
        _listArray = [NSMutableArray arrayWithArray:array];
        
        
        _hotArray = [NSMutableArray array];
        NSArray *hot = oneDic[@"hot"];
        for (NSDictionary *hotModel in hot) {
            MqMainbrandModel *model = [[MqMainbrandModel alloc] init];
            [model setValuesForKeysWithDictionary:hotModel];
            [_hotArray addObject:model];
        }
        
        
        //给表头赋值
        for (int i = 0; i < 4; i ++) {
            UIButton *button = [_headView viewWithTag:10 + i];
            MqMainbrandModel *model = _hotArray[i];
            [button addTarget:self action:@selector(buttonHeadClick:) forControlEvents:(UIControlEventTouchUpInside)];
            NSArray *subStr = [model.name componentsSeparatedByString:@"/"];
            [button setTitle:subStr[1] forState:(UIControlStateNormal)];
            
        }
        
        
        //刷新
        [self.tableView reloadData];
    } error:^(NSError *error) {
      
    } path:@"brandFile"];
}


- (void)buttonHeadClick:(UIButton *)button
{
    MqDetailBrandViewController *detailbrandVC = [[MqDetailBrandViewController alloc] init];
    NSInteger x = button.tag - 10;
    MqMainbrandModel *model = _hotArray[x];
    
    detailbrandVC.brand_id = model.ID;
    detailbrandVC.name = model.name;
    [self.navigationController pushViewController:detailbrandVC animated:YES];
    
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source
//分区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return _listArray.count;
}
//行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    NSString *key = _listArray[section];
    NSArray *array = _listDic[key];
    return array.count;
}

//设置cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"brand" forIndexPath:indexPath];
    
    NSString *key = _listArray[indexPath.section];
    NSArray *array = _listDic[key];
    MqMainbrandModel *model = array[indexPath.row];
    
    cell.textLabel.text = model.name;
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:model.logo] placeholderImage:[UIImage imageNamed:@"bike"]];
    

    return cell;
}


//分区名
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return _listArray[section];
}


- (nullable NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView

{
   
    return _listArray;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    MqDetailBrandViewController *detailbrandVC = [[MqDetailBrandViewController alloc] init];
    
    NSString *key = _listArray[indexPath.section];
    NSArray *array = _listDic[key];
    MqMainbrandModel *model = array[indexPath.row];
    
    //传值
    detailbrandVC.brand_id = model.ID;
    
    NSLog(@"brand_id = %@",model.ID);
    detailbrandVC.name = model.name;
    
    [self.navigationController pushViewController:detailbrandVC animated:YES];
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
